import Taro, { Current } from '@tarojs/taro'
import React, { PureComponent } from 'react'
// 界面组件
import { View, Text, Image } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
import CTopbar from '@/components/CTopBar/index'
import CImage from '@/components/CImage/index'
import { course_detail_api, course_lower_api, toggle_lick_api } from './service'
import prefixZero from '@/utils/PrefixZero.ts'
// import formatSeconds from '@/utils/formatSeconds'
import lock from '@/assets/lock.png'
import './index.scss'
import like from '@/assets/like.png'
import dislike from '@/assets/dislike.png'
import GetTopBarInfo from '@/utils/GetTopBarInfo' //动态高度
/**
 * 课程详情
 */
type I = {
  system: string
  value: string
  current: number
  id: number
  isLike: boolean
  curriculumData: any
  lower_data: any
  isMore: boolean
  pageSize: number
  pageNum: number
  total: number
}
interface CourseDetails {
  state: I
}
class CourseDetails extends PureComponent<any> {
  constructor(props) {
    super(props)
    this.state = {
      system: '',
      value: '',
      current: 0,
      id: -1,
      isLike: false,
      curriculumData: {},
      lower_data: {},
      isMore: false, //是否还有更多数据 ==评论列表
      pageSize: 10,
      pageNum: 1,
      total: 0,
    }
  }
  componentWillMount() {
    Taro.showLoading()
    const { id } = Current.router?.params
    const system = Taro.getStorageSync('system')
    this.setState(
      {
        id: Number(id),
        system,
      },
      () => {
        this.get_course_detail()
        this.get_course_lower(this.state.current + 1)
      },
    )
  }
  // 获取详细信息
  get_course_detail() {
    const { id, pageSize, pageNum } = this.state
    course_detail_api(id).then(({ result, data }) => {
      Taro.hideLoading()
      this.setState({
        curriculumData: data,
        isLike: data.collect,
      })
    })
  }

  // 获取栏目列表
  get_course_lower(type) {
    const { id, pageSize, pageNum } = this.state
    course_lower_api(id, type, pageSize, pageNum).then(({ result, data }) => {
      // if (pageSize === data?.comment?.length) {
      //   this.setState({
      //     isMore: true,
      //   })
      // }
      this.setState({
        lower_data: data,
        firstClassId: data?.courses[0].id,
      })
    })
  }
  // 切换tags
  handleClick(value) {
    this.get_course_lower(value + 1)
    this.setState({
      current: value,
    })
  }

  // 切换喜欢
  toggleLick() {
    const id = this.state.id
    toggle_lick_api(id, 2).then(() => {
      this.get_course_detail()
    })
  }

  // 去订阅
  gotoPay(isPay) {
    const { system, curriculumData, firstClassId } = this.state
    // type=2 课程
    // type=1 测评
    const id = curriculumData.id
    if (!id) {
      Taro.showToast({
        title: '请稍后再试！',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    // if (system.indexOf('iOS') < 0) {
    if (isPay) {
      if (!firstClassId) {
        Taro.showToast({
          title: '暂无课程！',
          icon: 'none',
          duration: 2000,
          mask: true,
        })
        return
      }
      Taro.navigateTo({
        url: '/pages/College/VideoPlay/index?id=' + id + '&courseId=' + firstClassId,
      })
    } else {
      Taro.navigateTo({
        // type===2   线上课程类型
        url: '/pages/Pay/index?id=' + id + '&type=2',
      })
    }
    // } else {
    //   Taro.showModal({
    //     title: '提示',
    //     content: '十分抱歉，由于相关规范，您暂时无法测试',
    //     success: function (res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //       } else if (res.cancel) {
    //         console.log('用户点击取消')
    //       }
    //     },
    //   })
    // }
  }

  // 目录点击
  ClickAuditionChange(is_free, courseId) {
    const { id, curriculumData } = this.state
    if (!id) {
      Taro.showToast({
        title: '请稍后再试！',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    // if (curriculumData.isPay) {
    if (is_free === 0) {
      // 没有购买走
      Taro.showToast({
        title: '请先购买',
        icon: 'none',
        duration: 2000,
      })
    } else {
      // /试看  或者已经购买课程走
      Taro.navigateTo({
        url: '/pages/College/VideoPlay/index?id=' + id + '&courseId=' + courseId,
      })
    }
    // } else {
    //   Taro.showToast({
    //     title: '请先购买',
    //     icon: 'none',
    //     duration: 2000,
    //   })
    // }
  }

  onReachBottom() {
    const { pageNum, isMore, current } = this.state
    if (current === 2) {
      // if (isMore) {
      this.setState(
        {
          pageNum: pageNum + 1,
        },
        () => {
          // type=3  代表是评论tabs
          this.get_course_lower(3)
        },
      )
      // } else {
      //   Taro.showToast({
      //     icon: 'none',
      //     title: '没有数据啦',
      //     mask: true,
      //   })
      // }
    }
  }

  render() {
    const {
      system = '',
      isLike = false,
      curriculumData = {},
      lower_data: { courses = [], comment = [], remarks = '' },
    } = this.state

    const tabList = [{ title: '目录' }, { title: '课程简介' }, { title: '精彩评论' }]
    return (
      <View className='pagewrap' style={{ paddingTop: `${GetTopBarInfo().TopBarHeight}px` }}>
        <View className='header'>
          <CTopbar title={curriculumData.courseName} showBack></CTopbar>
        </View>
        <View className='colleg'>
          {/* 课程图片 */}
          <View className='imageContainer'>
            <CImage src={curriculumData.courseImg}></CImage>
          </View>
          {/* 课程介绍 */}
          <View className='padding25'>
            <View>
              <Text className='title'>{curriculumData.courseName}</Text>
            </View>
            <View className='flexNum'>
              <Text>共{curriculumData.courseNumber || 0}节课程</Text>
              <Text className='person'>已有{curriculumData.watchNumber || 0}人上课</Text>
            </View>
            <View className='flexPriceAndFollow'>
              {system.indexOf('iOS') < 0 ? (
                <View className='priceNum'>
                  {curriculumData.price ? (
                    <View>
                      <Text className='Sapplets'>￥</Text>
                      <Text>{String(curriculumData.price).split('.')[0]}</Text>
                      <Text>{String(curriculumData.price).split('.')[1]}</Text>
                    </View>
                  ) : (
                    <View className='priceNum'>免费</View>
                  )}
                </View>
              ) : (
                <View className='priceNum'>免费</View>
              )}
              {/* {system.indexOf('iOS') < 0 ? (
                <View className='priceNum'>
                  <Text className='Sapplets'>{courseName.price === 0 ? '' : '￥'}</Text>
                  {courseName.price === 0 ? (
                    '免费'
                  ) : (
                    <View>
                      <Text>{courseName.price.toString().split('.')[0]}</Text>
                      <Text>{courseName.price.toString().split('.')[1] ? '.' : ''}</Text>
                      <Text className='Sapplets'>{courseName.price.toString().split('.')[1]}</Text>
                    </View>
                  )}
                </View>
              ) : (
                <View className='priceNum'>免费</View>
              )} */}

              {/* 切换喜欢 */}
              <View className='flex_1'>
                <View
                  className='like_wrapper'
                  onClick={() => {
                    this.toggleLick()
                  }}
                >
                  {isLike ? <Image src={like} /> : <Image src={dislike} />}

                  <Text className='likeStyle'>{isLike ? '已关注' : '关注'}</Text>
                </View>
              </View>
            </View>
          </View>

          {/* tag切换栏 */}

          <View className='tabsWsrap'>
            <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
              <AtTabsPane current={this.state.current} index={0}>
                <View className='catalog'>
                  <Text className='catalogTitle'>目录</Text>
                </View>
                <View>
                  {courses.map((current, index) => {
                    return (
                      <View className='catalogItem' key={index} onClick={this.ClickAuditionChange.bind(this, current.is_free, current.id)}>
                        <View>{prefixZero(index, 2)}</View>
                        <View className='ItemMiddle'>
                          <Text className='ItemTime'>{current.classTitle}</Text>
                          {/* <Text className='ItemTime'>时长：{formatSeconds(current.classTime)}</Text> */}
                        </View>
                        {/* {curriculumData.isPay ? (
                          ''
                        ) : ( */}
                        <View className='rightslot'>
                          {/* is_free  0 收费  1免费试听    2  全部购买课程  可以一次性干完~~了 */}
                          {current.is_free === 1 ? (
                            <Text className='textSpan'>试听</Text>
                          ) : current.is_free === 2 ? (
                            ''
                          ) : (
                            <Image className='lock' src={lock} />
                          )}
                        </View>
                        {/* )} */}
                      </View>
                    )
                  })}
                </View>

                {/* 占位 */}
                <View className='margintop80'></View>
              </AtTabsPane>
              <AtTabsPane current={this.state.current} index={1}>
                <View className='introduction'>
                  <Text className='introductionTitle'>课程简介</Text>
                </View>
                {remarks ? <View className='richtext' dangerouslySetInnerHTML={{ __html: remarks }}></View> : ''}
                {/* <View className='richtext'>
                  <RichText nodes={remarks&&remarks}></RichText>
                </View> */}
                {/* 站位 */}
                <View className='margintop80'></View>
              </AtTabsPane>
              <AtTabsPane current={this.state.current} index={2}>
                <View className='GreatComments'>
                  <Text className='GreatCommentsTitle'>精彩评论</Text>
                </View>
                {comment.map((c, i) => {
                  return (
                    <View className='commentItem' key={i}>
                      <View className='authorImg'>
                        <CImage src={c.avatarUrl} circle></CImage>
                      </View>
                      <View className='commentRight'>
                        <View className='commentTop'>
                          <Text className='nickName'>{c.nickName}</Text>
                          <Text className='commentDate'>{c.gmtCreate}</Text>
                        </View>
                        <View className='commentContent'>{c.comment}</View>
                      </View>
                    </View>
                  )
                })}

                {/* 站位 */}
                <View className='margintop80'></View>
              </AtTabsPane>
            </AtTabs>
          </View>

          {/* 固定按钮 */}
          <View className='footerBtn' onClick={this.gotoPay.bind(this, curriculumData.isPay)}>
            {system.indexOf('iOS') < 0 ? (
              curriculumData.price !== 0 ? (
                curriculumData.isPay ? (
                  <Text>去观看</Text>
                ) : curriculumData.price ? (
                  <Text className='footerBtnSpan'>{'订阅￥' + curriculumData.price}</Text>
                ) : (
                  '免费观看'
                )
              ) : (
                <Text className='footerBtnSpan'>免费订阅</Text>
              )
            ) : (
              <Text className='footerBtnSpan'>免费观看</Text>
            )}
          </View>
        </View>
      </View>
    )
  }
}

export default CourseDetails
